from urllib.parse import parse_qs
from flask import Flask, request, jsonify
import logging
import uuid
from baidubce import exception as ex
from sms_sample_conf import zhzgv2_sms_client
import os

# 配置日志
logging.basicConfig(level=logging.INFO)
LOG = logging.getLogger(__name__)

# 配置签名ID和模板ID
signature_id = 'sms-sign-zleEik70019'
template_id = 'sms-tmpl-QxFmER15565'

app = Flask(__name__)

# 配置文件路径
PHONE_MAPPING_FILE = '/workspace/lyyj_yolv9e6/weights/demonstration_lyyj/phones.txt'


def load_phone_mapping(file_path):
    """从txt文件加载手机号映射配置"""
    phone_mapping = {}
    try:
        with open(file_path, 'r') as f:
            for line_number, line in enumerate(f, 1):
                line = line.strip()
                if not line:
                    continue

                # 检查分隔符
                if ':' not in line:
                    LOG.warning(f"忽略无效行 {line_number}: 缺少冒号分隔符 - {line}")
                    continue

                # 分割级别和手机号
                level_str, mobile = line.split(':', 1)
                level_str = level_str.strip()
                mobile = mobile.strip()

                # 验证级别格式
                if not level_str.isdigit():
                    LOG.warning(f"忽略无效行 {line_number}: 级别必须为整数 - {line}")
                    continue

                level = int(level_str)

                # 验证手机号非空
                if not mobile:
                    LOG.warning(f"忽略无效行 {line_number}: 手机号为空 - {line}")
                    continue

                phone_mapping[level] = mobile

        return phone_mapping

    except FileNotFoundError:
        LOG.error(f"手机号映射文件 {file_path} 不存在")
        raise
    except Exception as e:
        LOG.error(f"读取手机号映射文件时发生错误: {str(e)}")
        raise


@app.route('/send_sms', methods=['POST'])
def send_sms():
    """短信发送接口"""
    request_id = str(uuid.uuid4())
    print(f"[{request_id}] 收到短信发送请求")

    try:
        # 动态加载手机号映射配置
        if not os.path.exists(PHONE_MAPPING_FILE):
            raise FileNotFoundError(f"配置文件 {PHONE_MAPPING_FILE} 不存在")

        phone_mapping = load_phone_mapping(PHONE_MAPPING_FILE)
        LOG.info(f"成功加载手机号映射配置: {phone_mapping}")

        data = request.get_json()
        if not data:
            return jsonify({
                "requestId": request_id,
                "code": "1001",
                "message": "请求体为空或不是有效的JSON格式",
                "data": []
            }), 400

        # 参数校验
        required_fields = ['type', 'msg', 'time', 'level', 'camera_id']
        if not all(field in data for field in required_fields):
            print(f"[{request_id}] 参数校验失败: 缺少必要参数")
            return jsonify({
                "requestId": request_id,
                "code": "1001",
                "message": "缺少必要参数",
                "data": []
            }), 400

        # 获取并验证告警级别
        try:
            level = int(data['level'])
        except ValueError:
            print(f"[{request_id}] 参数校验失败: 告警级别必须为整数")
            return jsonify({
                "requestId": request_id,
                "code": "1003",
                "message": "无效的告警级别格式",
                "data": []
            }), 400

        # 获取手机号
        mobile = phone_mapping.get(level)
        if not mobile:
            print(f"[{request_id}] 告警级别 {level} 未配置手机号，跳过发送")
            return jsonify({
                "requestId": request_id,
                "code": "1000",
                "message": "成功",
                "data": [{
                    "code": "1005",
                    "message": "未配置手机号",
                    "mobile": None,
                    "messageId": None
                }]
            })

        # 构造短信内容
        content_var = {
            "SiteName": str(data['camera_id']),
            "Type": f"{data['msg']}-{data['time']}"
        }

        # 调用短信服务
        response = zhzgv2_sms_client.send_message(
            signature_id=signature_id,
            template_id=template_id,
            mobile=mobile,
            content_var_dict=content_var
        )

        # 构造成功响应
        return jsonify({
            "requestId": request_id,
            "code": "1000",
            "message": "成功",
            "data": [{
                "code": "1000",
                "message": "成功",
                "mobile": mobile,
                "messageId": f"{request_id}_{mobile}"
            }]
        })

    except ex.BceHttpClientError as e:
        error_msg = str(e)
        if isinstance(e.last_error, ex.BceServerError):
            error_msg = f"服务端错误 - Code: {e.last_error.code}, RequestId: {e.last_error.request_id}"
            LOG.error(error_msg)
            print(f"[{request_id}] 短信服务端错误: {error_msg}")
        else:
            LOG.error(f"客户端错误: {error_msg}")
            print(f"[{request_id}] 短信客户端错误: {error_msg}")

        return jsonify({
            "requestId": request_id,
            "code": "1002",
            "message": "短信发送失败",
            "data": []
        }), 500

    except Exception as e:
        LOG.error(f"系统异常: {str(e)}")
        print(f"[{request_id}] 系统异常: {str(e)}")
        return jsonify({
            "requestId": request_id,
            "code": "1004",
            "message": "系统内部错误",
            "data": []
        }), 500


if __name__ == '__main__':
    print("启动短信服务，监听端口 3899...")
    app.run(host='0.0.0.0', port=3899)